//
//  NetTool.m
//  ECBBusinessCamp
//
//  Created by rimi on 16/6/16.
//  Copyright © 2016年 邓毕华. All rights reserved.
//

#import "NetTool.h"

#import "AFNetworking.h"
#import "MainViewController.h"

@interface NetTool ()

@property (nonatomic, strong) AlertView * alertView; // 弹出视图

@end

@implementation NetTool

#pragma mark 🌷🌷🌷life cycle🌷🌷🌷
+ (instancetype)sharedTool {
    static NetTool * netTool = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        netTool = [[NetTool alloc] init];
        // 配置网络数据解析格式
        netTool.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
    });
    return netTool;
}

#pragma mark 🌷🌷🌷private methods🌷🌷🌷
- (void)requestMethod:(requestMethod)method loadingMsg:(NSString *)loadingMsg url:(NSString *)urlStr parameters:(id)parameters finish:(callBackBlock)finish {
    [MBProgressHUD showMessage:loadingMsg];
    if ([LoginUserInfo defaultUserInfo].sid) {
        [urlStr stringByAppendingString:[NSString stringWithFormat:@";JSESSIONID=%@", [LoginUserInfo defaultUserInfo].sid]];
    }
    if ([LoginUserInfo defaultUserInfo].token) {
        [parameters setObject:[LoginUserInfo defaultUserInfo].token forKey:@"token"];
    }
    
    if (method == GET) {
        // GET 请求
        [self GET:urlStr parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            finish(responseObject, nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            finish(nil, error);
        }];
    } else {
        // POST 请求
        [self POST:urlStr parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"status"] integerValue] == 104) {
                [MBProgressHUD hideHUD];
                UIViewController * rootVc = [UIApplication sharedApplication].keyWindow.rootViewController;
                // 添加视图
                [rootVc.view addSubview:self.alertView];
                
                // 自动布局
                [_alertView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.size.sizeOffset(CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT));
                    make.center.equalTo(rootVc.view);
                }];
                return ;
            }
            finish(responseObject, nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            finish(nil, error);
        }];
        }
}
- (void)requestMethod:(requestMethod)method loadingMsg:(NSString *)loadingMsg url:(NSString *)urlStr otherData:(NSDictionary *)otherDataDic parameters:(id)parameters finish:(callBackBlock)finish {
    [MBProgressHUD showMessage:loadingMsg];
    if ([LoginUserInfo defaultUserInfo].sid) {
        [urlStr stringByAppendingString:[NSString stringWithFormat:@";JSESSIONID=%@", [LoginUserInfo defaultUserInfo].sid]];
    }
    if ([LoginUserInfo defaultUserInfo].token) {
        [parameters setObject:[LoginUserInfo defaultUserInfo].token forKey:@"token"];
    }
    
    [self POST:urlStr parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:otherDataDic[@"data"] name:otherDataDic[@"key"] fileName:otherDataDic[@"fileName"] mimeType:otherDataDic[@"dataType"]];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"status"] integerValue] == 104) {
            [MBProgressHUD hideHUD];
            UIViewController * rootVc = [UIApplication sharedApplication].keyWindow.rootViewController;
            // 添加视图
            [rootVc.view addSubview:self.alertView];
            
            // 自动布局
            [_alertView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.size.sizeOffset(CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT));
                make.center.equalTo(rootVc.view);
            }];
            return ;
        }
        finish(responseObject, nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        finish(nil, error);
    }];
}

#pragma mark 🌷🌷🌷getters and setters🌷🌷🌷
- (AlertView *)alertView {
    if (!_alertView) {
        NSArray * buttonNames = @[@"取消", @"重新登录"];
        _alertView = [[AlertView alloc] initWithButtonNames:buttonNames selecIndex:^(NSInteger selectIndex) {
            // 移除弹出视图
            [_alertView removeFromSuperview];
            
            // 移除现在显示的视图与控制器
            MainViewController * rootVc = (MainViewController *)[UIApplication sharedApplication].keyWindow.rootViewController;
            UIViewController * topVc = rootVc.childViewControllers.lastObject;
            [topVc.view removeFromSuperview];
            [topVc removeFromParentViewController];
            
            // 添加登录视图
            UIStoryboard * mainSb = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
            UIViewController * loginVc = [mainSb instantiateViewControllerWithIdentifier:@"LoginViewController"];
            UIView * placeView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
            [placeView addSubview:loginVc.view];
            [rootVc addChildViewController:loginVc];
            [rootVc.view addSubview:placeView];
            
            // 将第一个按钮选中
            DBHTabBarView * tabBarView = rootVc.tabBarView;
            UIButton * selectBtn = [tabBarView viewWithTag:tabBarView.selectedBtnIndex];
            selectBtn.selected = false;
            UIButton * firstBtn = [tabBarView viewWithTag:10];
            firstBtn.selected = true;
        }];
    }
    return _alertView;
}

@end
